package com.situ.stl.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.stl.Service.ReserveService;
import com.situ.stl.dao.CourseMapper;
import com.situ.stl.dao.ReserveMapper;
import com.situ.stl.model.Course;
import com.situ.stl.model.Reserve;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class ReserveServiceImpl implements ReserveService {
    private ReserveMapper reserveMapper;
    private CourseMapper courseMapper;


    public ReserveServiceImpl(ReserveMapper reserveMapper, CourseMapper courseMapper) {
        this.reserveMapper = reserveMapper;
        this.courseMapper = courseMapper;
    }

    @Transactional
    //创建预约
    @Override
    public int add(Reserve reserve) throws Exception {
        //重复预约校验
        Reserve exist = reserveMapper.selectByMemberAndCourse(reserve.getMemberId(), reserve.getCourseId());
        if (!ObjectUtils.isEmpty(exist)) {
            throw new Exception("已经预约，不可再次预约");
        }

        //课程是否存在（原逻辑判断反了，已修复）
        Course course = courseMapper.selectById(reserve.getCourseId());
        if (ObjectUtils.isEmpty(course)) {  // 原代码是!ObjectUtils.isEmpty，会导致课程存在时抛异常，此处修复
            throw new Exception("课程不存在，无法预约");
        }

        //检验预约时间（原逻辑单位错误，已修复：1小时=3600000毫秒）
        Date courseTime = course.getTime();//课程开始时间
        Date reserveTime = reserve.getReserveTime() != null ? reserve.getReserveTime() : new Date();
        long diffMills = courseTime.getTime() - reserveTime.getTime();
        if (diffMills < 3600000) {  // 原代码是<1，修复为小于1小时（3600000毫秒）
            throw new Exception("必须在开课一小时以前预约");
        }

        return reserveMapper.insert(reserve);
    }

    //删除预约
    @Override
    public int remove(Integer id) throws Exception {
        //校验预约是否存在
        if (reserveMapper.selectById(id) == null) {
            throw new Exception("预约不存在，无法删除");
        }

        return reserveMapper.deleteById(id);
    }

    //更新预约
    @Override
    public int edit(Reserve reserve) throws Exception {
        //校验是否有预约
        if (reserveMapper.selectById(reserve.getId()) == null) {
            throw new Exception("预约不存在，无法更新");
        }
        // 若更新评分或者评语，自动填充评论时间
        if (reserve.getScore() != null || !ObjectUtils.isEmpty(reserve.getComment())) {
            reserve.setCommentTime(new Date());
        }

        return reserveMapper.updateById(reserve);
    }

    //批量更新状态
    @Override
    public int batchUpdateStatus(Integer status, List<Integer> ids) throws Exception {
        if (ids == null || ids.isEmpty()) {
            throw new Exception("请至少选择一条预约记录");
        }
        return reserveMapper.batchUpdateStatus(status, ids);
    }


    //根据ID查询
    @Override
    public Reserve getById(Integer id) {
        return reserveMapper.selectWithRelations(id);
    }

    //查询全部
    @Override
    public List<Reserve> getAll() {
        // 调用关联查询方法，确保名称字段有值
        return reserveMapper.selectWithRelationsList(Wrappers.emptyWrapper());
    }

    //多条件查询预约（核心修改：调用关联查询方法）
    @Override
    public List<Reserve> search(Reserve reserve) {
        LambdaQueryWrapper<Reserve> queryWrapper = Wrappers.lambdaQuery(reserve)
                .eq(reserve.getStatus() != null, Reserve::getStatus, reserve.getStatus())
                .ge(reserve.getScore() != null, Reserve::getScore, reserve.getScore())
                .like(!ObjectUtils.isEmpty(reserve.getComment()), Reserve::getComment, reserve.getComment())
                .ge(reserve.getReserveTime() != null, Reserve::getReserveTime, reserve.getReserveTime())
                .eq(reserve.getCourseId() != null, Reserve::getCourseId, reserve.getCourseId())
                .eq(reserve.getMemberId() != null, Reserve::getMemberId, reserve.getMemberId())

                //819 新增：添加memberName的筛选条件（关联member表的name字段）
                .apply(!ObjectUtils.isEmpty(reserve.getMemberName()),
                        "m.name like concat('%', {0}, '%')", reserve.getMemberName())
                .orderByDesc(Reserve::getReserveTime);

        // 筛选课程名称
        if (!ObjectUtils.isEmpty(reserve.getCourseName())) {
            queryWrapper.apply("c.name like concat('%', {0}, '%')", reserve.getCourseName());
        }

        // 筛选教练名称
        if (!ObjectUtils.isEmpty(reserve.getCoachName())) {
            queryWrapper.apply("ch.name like concat('%', {0}, '%')", reserve.getCoachName());
        }
        // 关键修改：使用关联查询方法，而非基础selectList
        return reserveMapper.selectWithRelationsList(queryWrapper);
    }

    //分页查询
    @Override
    public Page<Reserve> searchByPage(Integer pageNo, Integer pageSize, Reserve reserve, String memberName, String courseName) {
        // 处理默认分页参数
        pageNo = pageNo == null ? 1 : pageNo;
        pageSize = pageSize == null ? 10 : pageSize;

        // 构建分页对象
        Page<Reserve> page = new Page<>(pageNo, pageSize);

        // 构建查询条件
        LambdaQueryWrapper<Reserve> queryWrapper = Wrappers.lambdaQuery(reserve)
                .eq(reserve.getStatus() != null, Reserve::getStatus, reserve.getStatus())
                .ge(reserve.getScore() != null, Reserve::getScore, reserve.getScore())
                .like(!ObjectUtils.isEmpty(reserve.getComment()), Reserve::getComment, reserve.getComment())
                .ge(reserve.getReserveTime() != null, Reserve::getReserveTime, reserve.getReserveTime())
                .eq(reserve.getCourseId() != null, Reserve::getCourseId, reserve.getCourseId())
                .eq(reserve.getMemberId() != null, Reserve::getMemberId, reserve.getMemberId());

        if (!ObjectUtils.isEmpty(reserve.getMemberName())) {
            queryWrapper.apply("m.name like concat('%', {0}, '%')", reserve.getMemberName());
        }

        if (!ObjectUtils.isEmpty(reserve.getCourseName())) {
            queryWrapper.apply("c.name like concat('%', {0}, '%')", reserve.getCourseName());
        }

//        queryWrapper.apply("1=1 order by r.id asc");
        // 调用带关联查询的分页方法
        return reserveMapper.selectPageWithRelations(page, queryWrapper);
    }


    //查询会员的所有预约
    @Override
    public List<Reserve> getByMember(Integer memberId) {
        return reserveMapper.selectByMember(memberId);
    }

    //查询课程的所有预约
    @Override
    public List<Reserve> getByCourse(Integer courseId) {
        return reserveMapper.selectByCourse(courseId);
    }

    @Override
    public List<Reserve> selectByMemberNameAndCourseName(String memberName, String courseName) {
        return reserveMapper.selectByMemberNameAndCourseName(memberName, courseName);
    }
}